package com.db.logging;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class RaymanLogger {
	static final String DEBUG = "DEBUG";
	static final String ERROR = "ERROR";
	static final String INFO = "INFO";
	
	static final int QUEUE_CAPACITY = 1024;

	BlockingQueue<String> queue = new LinkedBlockingQueue<String>(QUEUE_CAPACITY);
	LoggerProcessor processor;
	PrintWriter writer;
	
	public RaymanLogger(String filename) throws FileNotFoundException {
		writer = new PrintWriter(filename);
		processor = new LoggerProcessor();
		Thread t = new Thread(processor);
		t.setDaemon(true);
		t.start();
	}

	public void debug(String arg0) {
		log(formatMessage(DEBUG, arg0));
	}

	public void debug(String arg0, Object arg1) {
		log(formatMessage(DEBUG, arg0, arg1));		
	}

	public void error(String arg0) {
		log(formatMessage(ERROR, arg0));		
	}

	public void error(String arg0, Object arg1) {
		log(formatMessage(ERROR, arg0, arg1));
	}

	public void info(String arg0) {
		log(formatMessage(INFO, arg0));
	}

	public void info(String arg0, Object arg1) {
		log(formatMessage(INFO, arg0, arg1));		
	}

	private void log(String message) {
		queue.add(message);
	}
	
	private String formatMessage(String header, String message) {
		return new StringBuilder(header).append(": ").append(message).toString();
	}
	
	private String formatMessage(String header, String message, Object obj) {		
		return new StringBuilder(header).append(": ").append(message.replaceFirst("\\{\\}", obj.toString())).toString();
	}
	
	private class LoggerProcessor implements Runnable {
		
		@Override
		public void run() {
			while (true) {
				try {
					String message = queue.take();
					writer.println(message);
					writer.flush();
				} catch (InterruptedException e) { }
			}
		}		
	}
}
